package club.bigtian.sync.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;

import javax.sql.DataSource;

/**
 * 数据源配置类
 * 用于配置MySQL和ClickHouse连接
 */
@Configuration
public class DataSourceConfig {

    // MySQL配置
    @Value("${mysql.host}")
    private String mysqlHost;

    @Value("${mysql.port}")
    private int mysqlPort;

    @Value("${mysql.username}")
    private String mysqlUsername;

    @Value("${mysql.password}")
    private String mysqlPassword;

    @Value("${mysql.database}")
    private String mysqlDatabase;

    // ClickHouse配置
    @Value("${clickhouse.host}")
    private String clickhouseHost;

    @Value("${clickhouse.port}")
    private int clickhousePort;

    @Value("${clickhouse.username}")
    private String clickhouseUsername;

    @Value("${clickhouse.password}")
    private String clickhousePassword;

    @Value("${clickhouse.database}")
    private String clickhouseDatabase;

    /**
     * MySQL数据源
     */
    @Bean(name = "mysqlDataSource")
    public DataSource mysqlDataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
        dataSource.setUrl(String.format("jdbc:mysql://%s:%d/%s?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC", 
                mysqlHost, mysqlPort, mysqlDatabase));
        dataSource.setUsername(mysqlUsername);
        dataSource.setPassword(mysqlPassword);
        return dataSource;
    }

    /**
     * MySQL JdbcTemplate
     */
    @Bean(name = "mysqlJdbcTemplate")
    public JdbcTemplate mysqlJdbcTemplate() {
        return new JdbcTemplate(mysqlDataSource());
    }

    /**
     * ClickHouse数据源
     */
    @Bean(name = "clickhouseDataSource")
    public DataSource clickhouseDataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName("ru.yandex.clickhouse.ClickHouseDriver");
        dataSource.setUrl(String.format("jdbc:clickhouse://%s:%d/%s", 
                clickhouseHost, clickhousePort, clickhouseDatabase));
        dataSource.setUsername(clickhouseUsername);
        dataSource.setPassword(clickhousePassword);
        return dataSource;
    }

    /**
     * ClickHouse JdbcTemplate
     */
    @Bean(name = "clickhouseJdbcTemplate")
    public JdbcTemplate clickhouseJdbcTemplate() {
        return new JdbcTemplate(clickhouseDataSource());
    }
} 